package com.zhangdi.dwtools.security;

import com.zhangdi.dwtools.consts.ConstValue;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;

public class Digests {
    private final static SecureRandom random = new SecureRandom();

    public static byte[] generateSalt(int numBytes) {

        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        return bytes;
    }

    public static byte[] sha1(byte[] input) {
        return digest(input, ConstValue.ALGORITHM_SHA_1, null, 1);
    }

    public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
        return digest(input, ConstValue.ALGORITHM_SHA_1, salt, iterations);
    }

    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            if (salt != null) {
                digest.update(salt);
            }
            byte[] result = digest.digest(input);
            for(int i = 1; i < iterations; ++i) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static byte[] md5(InputStream input) throws IOException {
        return digest(input, ConstValue.ALGORITHM_MD_5);
    }

    public static byte[] sha1(InputStream input) throws IOException {
        return digest(input, ConstValue.ALGORITHM_SHA_1);
    }

    private static byte[] digest(InputStream input, String algorithm) throws IOException {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            int bufferLength = 8192;
            byte[] buffer = new byte[bufferLength];

            for(int read = input.read(buffer, 0, bufferLength); read > -1; read = input.read(buffer, 0, bufferLength)) {
                messageDigest.update(buffer, 0, read);
            }

            return messageDigest.digest();
        } catch (GeneralSecurityException var6) {
            var6.printStackTrace();
        }

        return null;
    }
}
